<template>
  <div style="background-color: #f0f3fb; padding: 10px">
    <div style="background-color: #fff; border-radius: 5px; padding: 10px">
      <div style="display: flex">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
        <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">基础信息</div>
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商户名称:</div>
        <input v-model="spForm.merName" class="input_class" placeholder="请填写商户名称" />
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">联系人:</div>
        <input v-model="spForm.realName" class="input_class" placeholder="请填写联系人" />
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">手机号:</div>
        <input v-model="spForm.merPhone" type="number" class="input_class" placeholder="请填写手机号" />
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">地址:</div>
        <input v-model="spForm.merAddress" class="input_class" placeholder="请填写地址" />
      </div>
      <div style="display: flex">
        <div style="width: 90px; margin-top: 15px">店铺简介:</div>
        <div class="editor-wrapper">
          <Rboy-editor ref="RboyEditor" @uploadFile="uploadFile" :count="6"></Rboy-editor>
        </div>
      </div>
    </div>
    <div style="background-color: #fff; border-radius: 5px; padding: 10px; margin-top: 15px">
      <div style="display: flex; padding: 10px">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
        <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">详细信息</div>
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商户头像:</div>
        <div style="margin-top: 15px">
          <u-upload :fileList="avatarFileList" @afterRead="afterRead" height="200" width="200" @delete="deletePic" name="avatar" :maxCount="10" :previewFullImage="true">
            <view class="upload-placeholder">
              <u-icon name="plus" size="28" color="#999"></u-icon>
              <text class="upload-text">上传图片</text>
            </view>
          </u-upload>
        </div>
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商户banner:</div>
        <div style="margin-top: 15px">
          <u-upload :fileList="bannerFileList" @afterRead="afterReadBanner" height="200" width="200" @delete="deletePic" name="banner" :maxCount="10" :previewFullImage="true">
            <view class="upload-placeholder">
              <u-icon name="plus" size="28" color="#999"></u-icon>
              <text class="upload-text">上传图片</text>
            </view>
          </u-upload>
        </div>
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">营业执照:</div>
        <div style="margin-top: 15px">
          <u-upload :fileList="licenseFileList" @afterRead="afterReadYyzz" height="200" width="200" @delete="deletePic" name="license" :maxCount="10" :previewFullImage="true">
            <view class="upload-placeholder">
              <u-icon name="plus" size="28" color="#999"></u-icon>
              <text class="upload-text">上传图片</text>
            </view>
          </u-upload>
        </div>
      </div>
      <u-picker :show="showType" @cancel="showType = false" :columns="columns" keyName="categoryName" @confirm="getTsType"></u-picker>
    </div>
    <u-button type="primary" @click="addOwner">保存</u-button>
  </div>
</template>

<script>
import RboyEditor from '../../components/Rboy-editor/Rboy-editor.vue';
import { getUserInfo, updateMer } from '../../utils/merorder/mer';
export default {
  components: {
    RboyEditor
  },
  data() {
    return {
      myInfo: {},
      spForm: {},
      imgurl: uni.getStorageSync('imgurl'),
      showType: false,
      columns: [],
      avatarFileList: [],
      bannerFileList: [],
      licenseFileList: [],
      typeValue1: '请选择商品类型',
      typeValue: '请选择是否上架',
      xiaoqumingc: '请选择小区',
      isType: '1',
      title: '',
      content: '',
      complaintCategory: '',
      complaintCategorys: '',
      estateId: '',
      fileName: '',
      images: '',
      spForm: {
        image: '',
        storeName: '',
        storeInfo: '',
        price: '',
        isShow: '',
        merId: '',
        storeType: '',
        giveIntegral: '',
        canUseIntegral: '',
        stock: '',
        unitName: ''
      }
    };
  },
  onLoad() {
    getUserInfo(uni.getStorageSync('merId')).then((res) => {
      this.spForm = res.data;
      this.initImageFiles();
      this.$nextTick(() => {
        setTimeout(() => {
          if (this.$refs.RboyEditor && this.spForm.merInfo) {
            this.$refs.RboyEditor.editor_setContents(this.spForm.merInfo);
          }
        }, 1000);
      });
    });
  },
  methods: {
    initImageFiles() {
      // 初始化图片回显
      if (this.spForm.merAvatar) {
        const avatarPaths = this.spForm.merAvatar.split(',');
        this.avatarFileList = avatarPaths.map((path) => ({
          url: this.imgurl + path,
          fileName: path
        }));
      }

      if (this.spForm.merBanner) {
        const bannerPaths = this.spForm.merBanner.split(',');
        this.bannerFileList = bannerPaths.map((path) => ({
          url: this.imgurl + path,
          fileName: path
        }));
      }

      if (this.spForm.miniBanner) {
        const licensePaths = this.spForm.miniBanner.split(',');
        this.licenseFileList = licensePaths.map((path) => ({
          url: this.imgurl + path,
          fileName: path
        }));
      }
    },
    async get_content() {
      if (this.$refs.RboyEditor) {
        this.spForm.merInfo = await this.$refs.RboyEditor.editor_getcontents();
      }
    },
    async uploadFile(event) {
      for (let item in event.tempFilePaths) {
        let src = await this.uploadFilePromise(event.tempFilePaths[item]);
        this.$refs.RboyEditor.editor_insertImage({
          src: 'https://www.wantongkonggu.cn/' + src.fileName,
          alt: '图像'
        });
      }
    },
    getSpInfo() {
      productInfo(this.spId).then((res) => {
        this.spForm = res.data;
        this.typeValue1 = res.data.categoryName;
        this.typeValue = res.data.isShow == 0 ? '是' : '否';
        this.images = 'https://www.wantongkonggu.cn/' + res.data.image;
        this.fileName = res.data.image;
        this.merchantCategoryId = res.data.isShow;
        this.complaintCategorys = res.data.storeType;
      });
    },
    getUserInfo() {
      var userInfo = uni.getStorageSync('userInfo');
      var e = {
        merId: userInfo ? userInfo.merId : '',
        merName: ''
      };
      merlist(e).then((res) => {});
    },
    getType() {
      categorylist().then((res) => {
        this.isType = 2;
        this.showType = true;
        this.columns = [res.rows];
      });
    },
    getestate() {
      estateapppage({ size: 200 }).then((res) => {
        res.data.records.forEach((item) => {
          item.dictValue = item.name;
        });
        this.columns = [res.data.records];
        this.isType = 3;
        this.showType = true;
      });
    },
    async addOwner() {
      await this.get_content();
      updateMer(this.spForm).then((res) => {
        if (res.code == 200) {
          uni.showToast({
            icon: 'none',
            title: '操作成功！'
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
              animationType: 'pop-out',
              animationDuration: 200
            });
          }, 1500);
        }
      });
    },
    getTsType({ value }) {
      this.showType = false;
      if (this.isType == 1) {
        this.typeValue = value[0].categoryName;
        this.complaintCategory = value[0].merchantCategoryId;
      } else if (this.isType == 2) {
        this.typeValue1 = value[0].categoryName;
        this.complaintCategorys = value[0].merchantCategoryId;
      }
    },
    getTypelx() {
      this.isType = 1;
      this.showType = true;
      this.columns = [
        [
          { categoryName: '是', merchantCategoryId: '1' },
          { categoryName: '否', merchantCategoryId: '2' }
        ]
      ];
    },
    // 删除图片
    deletePic(event) {
      // 根据name属性区分不同上传组件的删除事件
      switch (event.name) {
        case 'avatar':
          this.avatarFileList.splice(event.index, 1);
          // 更新spForm中的值为逗号分隔的字符串
          this.spForm.merAvatar = this.avatarFileList.map((item) => item.fileName).join(',');
          break;
        case 'banner':
          this.bannerFileList.splice(event.index, 1);
          // 更新spForm中的值为逗号分隔的字符串
          this.spForm.merBanner = this.bannerFileList.map((item) => item.fileName).join(',');
          break;
        case 'license':
          this.licenseFileList.splice(event.index, 1);
          // 更新spForm中的值为逗号分隔的字符串
          this.spForm.miniBanner = this.licenseFileList.map((item) => item.fileName).join(',');
          break;
      }
    },
    // 新增图片
    async afterRead(event) {
      console.log(event);
      const result = await this.uploadFilePromise(event.file.url);

      // 添加到fileList而不是替换
      this.avatarFileList.push({
        url: this.imgurl + result.fileName,
        fileName: result.fileName
      });

      // 更新spForm中的值为逗号分隔的字符串
      this.spForm.merAvatar = this.avatarFileList.map((item) => item.fileName).join(',');
      console.log(this.avatarFileList);
    },
    // 新增图片
    async afterReadBanner(event) {
      console.log(event);
      const result = await this.uploadFilePromise(event.file.url);

      // 添加到fileList而不是替换
      this.bannerFileList.push({
        url: this.imgurl + result.fileName,
        fileName: result.fileName
      });

      // 更新spForm中的值为逗号分隔的字符串
      this.spForm.merBanner = this.bannerFileList.map((item) => item.fileName).join(',');
      console.log(this.bannerFileList);
    },
    // 新增图片
    async afterReadYyzz(event) {
      console.log(event);
      const result = await this.uploadFilePromise(event.file.url);

      // 添加到fileList而不是替换
      this.licenseFileList.push({
        url: this.imgurl + result.fileName,
        fileName: result.fileName
      });

      // 更新spForm中的值为逗号分隔的字符串
      this.spForm.miniBanner = this.licenseFileList.map((item) => item.fileName).join(',');
      console.log(this.licenseFileList);
    },
    uploadFilePromise(url) {
      const userInfo = uni.getStorageSync('userInfo');
      const token = userInfo ? userInfo.token : '';
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          header: {
            'Authori-zation': token
          },
          url: 'https://www.wantongkonggu.cn//api/adminApph7/common/upload',
          filePath: url,
          name: 'file',
          formData: {
            user: 'test'
          },
          success: (res) => {
            console.log(res);
            resolve(JSON.parse(res.data));
          }
        });
      });
    }
  }
};
</script>

<style lang="scss">
.textarea_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}

.input_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}

.editor-wrapper {
  width: calc(100% - 100px);
  margin-top: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.upload-placeholder {
  border: 1px dashed #c0c4cc;
  border-radius: 4px;
  width: 200rpx;
  height: 200rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}
</style>
